<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="myHandleAdd" type="primary" icon="plus">新增</a-button> -->
      <a-button type="primary" icon="download" @click="handleExportXls('项目运维表')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
        @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"></j-super-query>
      <!-- <a-button type="primary" icon="plus" @click="goToMaintenanceTemplateList()">运维内容</a-button> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
          selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        <!-- <span style="float:right;">
          <a @click="loadData()"><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <list-columns-fix-setter
            v-if="columns.length > 0"
            v-model="columns"
            :def-columns="columns"
            @change="columnChange"
          />
        </span> -->
      </div>

      <a-table ref="table" size="middle" :scroll="{ x: true }" bordered rowKey="id" :columns="columns"
        :dataSource="dataSource" :pagination="ipagination" :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record" style="display: flex;">
          <a-popconfirm v-show="record.maintenanceStatus<=1||!record.maintenanceStatus" :title="record.maintenanceStatus == '0' || !record.maintenanceStatus ? '确定接单吗?' : '确定处理吗?'"
            @confirm="() => updateRecord(record)">
            <a>{{ record.maintenanceStatus == '0' || !record.maintenanceStatus ? '接单' : '处理' }}</a>
          </a-popconfirm>
          <a-divider v-show="record.maintenanceStatus<=1||!record.maintenanceStatus" type="vertical" />
          <!-- <a-menu-item> -->
            <a @click="handleDetail(record)">详情</a>
          <!-- </a-menu-item> -->
          <a-divider type="vertical" v-show="record.maintenanceStatus!=3"/>
          <!-- <a-menu-item > -->
            <a-popconfirm v-show="record.maintenanceStatus!=3" :title="record.maintenanceStatus == 2 || !record.maintenanceStatus ? '确定完成吗?' : '确定放弃吗?'"
              @confirm="() => record.maintenanceStatus == 2?finishRecord(record):handleDelete(record.id)">
              <a>{{ record.maintenanceStatus == 2 ? '完成' : '放弃' }}</a>
            </a-popconfirm>
          <!-- </a-menu-item> -->
        </span>

      </a-table>
    </div>

    <yks-equipment-devops-plan-modal ref="modalForm" @ok="modalFormOk"></yks-equipment-devops-plan-modal>
  </a-card>
</template>
  
<script>

import { httpAction, getAction } from '@/api/manage'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import YksEquipmentDevopsPlanModal from './modules/YksEquipmentDevopsPlanModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { filterObj } from '@/utils/util';
import moment from 'dayjs'

export default {
  name: 'YksEquipmentDevopsPlanList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    YksEquipmentDevopsPlanModal
  },
  data() {
    return {
      description: '项目运维页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '名称',
          align: "center",
          dataIndex: 'name'
        },
        {
          title: '项目',
          align: "center",
          dataIndex: 'equipmentId_dictText'
        },
        {
          title: '运维类型',
          align: "center",
          dataIndex: 'devopsPersontype_dictText'
        },
        {
          title: '运维人员',
          align: "center",
          dataIndex: 'maintenancePerson_dictText'
        },
        {
          title: '运维部门',
          align: "center",
          dataIndex: 'maintenanceDept_dictText'
        },
        {
          title: '触发类型',
          align: "center",
          dataIndex: 'triggerType_dictText'
        },
        {
          title: '初次触发时间',
          align: "center",
          dataIndex: 'triggerTime',
          customRender: function (text) {
            return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '重复次数',
          align: "center",
          dataIndex: 'repeatNumber'
        },
        {
          title: '重复间隔',
          align: "center",
          dataIndex: 'repeatGap'
        },
        {
          title: '重复间隔单位',
          align: "center",
          dataIndex: 'repeatGapUnit_dictText'
        },
        {
          title: '上次保养时间',
          align: "center",
          dataIndex: 'maintenanceLastTime',
          customRender: function (text) {
            return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '下次机会保养时间',
          align: "center",
          dataIndex: 'maintenanceNextTime',
          customRender: function (text) {
            return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '保养时间段开始',
          align: "center",
          dataIndex: 'maintenanceQuantumstart',
          customRender: function (text) {
            return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '保养时间段结束',
          align: "center",
          dataIndex: 'maintenanceQuantumend',
          customRender: function (text) {
            return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '保养类型',
          align: "center",
          dataIndex: 'maintenanceType_dictText'
        },
        {
          title: '保养内容',
          align: "center",
          dataIndex: 'maintenanceContext'
        },
        {
          title: '模版ID',
          align: "center",
          dataIndex: 'templateId_dictText'
        },
        {
          title: '运维状态',
          align: "center",
          dataIndex: 'maintenanceStatus_dictText',
          //   customRender:function (text) {
          //   return !text||text=='0'?"待接单":(text=="1"?"处理中":"已完成")
          // }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: "/dev/yksEquipmentDevops/list",
        delete: "/dev/yksEquipmentDevops/delete",
        deleteBatch: "/dev/yksEquipmentDevops/deleteBatch",
        exportXlsUrl: "/dev/yksEquipmentDevops/exportXls",
        importExcelUrl: "dev/yksEquipmentDevops/importExcel",
        edit: "/dev/yksEquipmentDevops/edit",

      },
      currentEquipmentId: '',
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  methods: {
    myHandleAdd: function () {
      this.$refs.modalForm.currentEquipmentId = this.currentEquipmentId
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    open(record) {
      this.currentEquipmentId = record.id
      this.loadData(1)
    },
    loadData(arg) {
      debugger
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      params.equipmentId = this.currentEquipmentId
      // params.maintenanceNextTime=new Date().getDate()
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result;
          if (res.result.total) {
            this.ipagination.total = res.result.total;
          } else {
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      let superArr = []
      if (param.superQueryParams) {
        superArr = JSON.parse(decodeURI(param.superQueryParams))
      } else {
        param.superQueryMatchType = 'and'
      }
      //le小于等于,ge大于等于，gt大于,lt小于
      superArr.push({ rule: 'le', type: 'string', dictCode: '', val: moment(new Date()).format('YYYY-MM-DD'), field: 'maintenanceNextTime' })
      superArr.push({ rule: 'le', type: 'int', dictCode: 'maintenance_status', val: 2, field: 'maintenanceStatus' })
      // superArr.push({ rule: 'ge', type: 'int', dictCode: '', val: 1, field: 'repeatNumber' })
      // superArr.push({ rule: 'eq', type: 'string', dictCode: '', val: processId, field: 'processId' })
      // if (this.action == 'edit') {
      //   superArr.push({
      //     rule: 'eq',
      //     type: 'string',
      //     dictCode: '',
      //     val: this.currentWorkOrderItemId,
      //     field: 'workOrderItemId',
      //   })

      // }
      // if (this.action == 'edit' || this.action == 'query') {
      //   superArr.push({ rule: 'eq', type: 'string', dictCode: '', val: this.planQueryDate, field: 'planDate' })
      // }
      // console.log(param.bomFlag, typeof param.bomFlag)

      if (superArr.length > 0) {
        param.superQueryParams = encodeURI(JSON.stringify(superArr))
      }
      return filterObj(param);
    },
    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: 'string', value: 'name', text: '名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'equipmentId', text: '项目', dictCode: "yks_equipment,name,id" })
      fieldList.push({ type: 'string', value: 'devopsPersontype', text: '运维类型', dictCode: 'devops_persontype' })
      fieldList.push({ type: 'string', value: 'maintenancePerson', text: '运维人员', dictCode: "sys_user,username,id" })
      fieldList.push({ type: 'string', value: 'maintenanceDept', text: '运维部门', dictCode: "sys_depart,depart_name,id" })
      fieldList.push({ type: 'string', value: 'triggerType', text: '触发类型', dictCode: 'trigger_type' })
      fieldList.push({ type: 'date', value: 'triggerTime', text: '初次触发时间' })
      fieldList.push({ type: 'string', value: 'repeatNumber', text: '重复次数', dictCode: '' })
      fieldList.push({ type: 'string', value: 'repeatGap', text: '重复间隔', dictCode: '' })
      fieldList.push({ type: 'string', value: 'repeatGapUnit', text: '重复间隔单位', dictCode: "yks_unit,name,id" })
      fieldList.push({ type: 'date', value: 'maintenanceLastTime', text: '上次保养时间' })
      fieldList.push({ type: 'date', value: 'maintenanceNextTime', text: '下次机会保养时间' })
      fieldList.push({ type: 'date', value: 'maintenanceQuantumstart', text: '保养时间段开始' })
      fieldList.push({ type: 'date', value: 'maintenanceQuantumend', text: '保养时间段结束' })
      fieldList.push({ type: 'string', value: 'maintenanceType', text: '保养类型', dictCode: 'maintenance_type' })
      fieldList.push({ type: 'string', value: 'maintenanceContext', text: '保养内容', dictCode: '' })
      fieldList.push({ type: 'string', value: 'templateId', text: '模版ID', dictCode: "yks_maintenance_template,template_name,id" })
      fieldList.push({ type: 'int', value: 'maintenanceStatus', text: '运维状态', dictCode: 'maintenance_status' })
      this.superFieldList = fieldList
    },
    //跳转到保养内容维护界面
    // goToMaintenanceTemplateList(){
    //   this.$router.push(YksMaintenanceTemplateListVue)
    // }
    updateRecord(record) {
      let that = this
      let httpurl = this.url.edit;
      let method = 'put';
      let msg = ''
      if (!record.maintenanceStatus || record.maintenanceStatus == '0') {
        record.maintenanceStatus = '1'
        msg = '接单'
        httpAction(httpurl, record, method).then((res) => {
          if (res.success) {
            that.$message.success(msg + '成功！');
            that.$emit('ok');
          } else {
            that.$message.warning(msg + "失败:" + res.message);
          }
        }).finally(() => {
          //   that.confirmLoading = false;
        })
      }
      else if (record.maintenanceStatus == '1') {
        this.handleEdit(record)
      }

    },
    finishRecord(record){
      let that = this
      let httpurl = this.url.edit;
      let method = 'put';
      let msg = ''
      if ( record.maintenanceStatus == '2') {
        if(record.repeatNumber>1){//还会有下一次保养
          record.repeatNumber=record.repeatNumber-1
            if(moment(record.maintenanceNextTime).isBefore.moment(new Date()).format('YYYY-MM-DD')
            ||moment(record.maintenanceNextTime).isSame.moment(new Date()).format('YYYY-MM-DD')){
          if(record.repeatGapUnit_dictText=='天'||record.repeatGapUnit_dictText=='日')
              record.maintenanceNextTime=moment(new Date()).format('YYYY-MM-DD').add(record.repeatGap,'day')
            }else if(record.repeatGapUnit_dictText=='月'){
              record.maintenanceNextTime=moment(new Date()).format('YYYY-MM-DD').add(record.repeatGap,'month')
            }else if(record.repeatGapUnit_dictText=='年'){
              record.maintenanceNextTime=moment(new Date()).format('YYYY-MM-DD').add(record.repeatGap,'month')
            }
            record.maintenanceStatus = '0'//重置为待接单
          }else{
            record.repeatNumber=0
            record.maintenanceStatus = '3'
          }
        
      
        msg = '确认完成'
        httpAction(httpurl, record, method).then((res) => {
          if (res.success) {
            that.$message.success(msg + '成功！');
            loadData(1)
            that.$emit('ok');
          } else {
            that.$message.warning(msg + "失败:" + res.message);
          }
        }).finally(() => {
          
        })
      }
    },
    
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>